<?php
namespace app\admin\controller;

use app\common\lib\AliSms;
use app\common\model\SmsCodeModel;

class Dev extends Common
{
    /**
     * 快捷开发
     * @author 贺强
     * @time   2023/5/19 9:06
     */
    public function index()
    {
        return view();
    }

    /**
     * 创建手机验证码
     * @author 贺强
     * @time   2023/5/19 11:19
     * @return string|\think\response\Json
     */
    public function create_sms_code()
    {
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $mobile = $this->request->post('mobile', '');
        if (empty($mobile)) {
            return ajax('手机号不能为空', 101);
        }
        if (!is_mobile($mobile)) {
            return ajax('手机号不合法', 301);
        }
        SmsCodeModel::delByWhere(['mobile' => $mobile]);
        $code = get_random_num();
        $data = compact('mobile', 'code');
        $res = SmsCodeModel::add($data);
        if ($res) {
            return ajax('创建成功', 200, $code);
        }
        return ajax('创建失败', 400);
    }

    /**
     * 发送手机验证码
     * @author 贺强
     * @time   2023/5/19 11:32
     * @return string|\think\response\Json
     */
    public function send_sms_code()
    {
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $mobile = $this->request->post('mobile', '');
        if (empty($mobile)) {
            return ajax('手机号不能为空', 101);
        }
        if (!is_mobile($mobile)) {
            return ajax('手机号不合法', 301);
        }
        SmsCodeModel::delByWhere(['mobile' => $mobile]);
        $code = get_random_num();
        $data = compact('mobile', 'code');
        $res = SmsCodeModel::add($data);
        if (!$res) {
            return ajax('创建失败', 400);
        }
        $flag = AliSms::sendVerifyCode($mobile, $code);
        if (!$flag) {
            return ajax('短信发送失败', 302);
        }
        return ajax('发送成功');
    }
}
